package com.tanhua.dubbo.api;

import com.tanhua.dubbo.api.mongo.MovementApi;
import com.tanhua.dubbo.async.TimeLineService;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.vo.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 推荐用户服务接口实现类
 */
@DubboService
@Slf4j
public class MovementApiImpl implements MovementApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private TimeLineService timeLineService;

    /**
     * 发布动态
     *
     * @param movement
     */
    @Override
    public void add(Movement movement) {
        log.debug("**********发布动态{}**********",movement.toString());
        long nowTime = System.currentTimeMillis();
        Long loginUserId = movement.getUserId();//当前登录用户id
        //1将动态数据保存动态表
        movement.setId(ObjectId.get());//可以不设置 可以自动生成
        movement.setPid(idWorker.getNextId("movement"));//推荐系统使用Pid(这个值自动增长的，唯一值)
        movement.setCreated(nowTime);//动态发布时间
        mongoTemplate.insert(movement);
        log.debug("**********保存动态表成功了**********");

        //2异步调用addTimeLines
        log.debug("**********开始异步调用addTimeLines方法***********");
        timeLineService.addTimeLines(loginUserId,movement);
        log.debug("**********结束异步调用addTimeLines方法**********");

        /*//2查询好友表获取所有好友ids
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(loginUserId));
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
        log.debug("**********查询好友表{}**********",friendList.toString());
        //3往好友时间线表插入数据
        if(!CollectionUtils.isEmpty(friendList)){
            for (Friend friend : friendList) {
                MovementTimeLine movementTimeLine = new MovementTimeLine();
                movementTimeLine.setMovementId(movement.getId());//动态id(保存动态表主键id)
                movementTimeLine.setUserId(loginUserId);//发布动态用户id
                movementTimeLine.setFriendId(friend.getFriendId());//可见好友id
                movementTimeLine.setCreated(nowTime);
                mongoTemplate.insert(movementTimeLine);
            }
        }
        log.debug("*********循环插入时间线表数据成功了**********");*/
    }

    /**
     * 根据用户id分页查询动态表数据
     *
     * @param page
     * @param pageSize
     * @param userId
     * @return
     */
    @Override
    public PageResult<Movement> findPageMovement(Long page, Long pageSize, Long userId) {
        long start = (page-1)*pageSize;//从那条开始查询 （page-1）*pageSize
        //1.查询总记录数
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));//where userId = 1
        long count = mongoTemplate.count(query, Movement.class);
        //2.每页展示的数据
        query.skip(start).limit(pageSize.intValue());
        //2.1根据userId排序
        //1.1 排序created 最新发布的动态发到最上面
        query.with(Sort.by(Sort.Direction.DESC,"created"));
        List<Movement> movementList = mongoTemplate.find(query, Movement.class);
        return new PageResult<>(page,pageSize,count,movementList);
    }

    /**
     * 好友动态
     *
     * @param page
     * @param pageSize
     * @param loginUserId
     */
    @Override
    public PageResult<Movement> findPageMovementByFriend(Long page, Long pageSize, Long loginUserId) {
        //1.分页查询好友时间表
        //1.1查询好友时间线表总记录数
        Query query = new Query();
        query.addCriteria(Criteria.where("friendId").is(loginUserId));
        long count = mongoTemplate.count(query, MovementTimeLine.class);
        //1.2查询当前页面展示的分页数据（好友数据）
        long start = (page-1)*pageSize;//从那条开始查询 （page-1）*pageSize
        query.skip(start).limit(pageSize.intValue());
        query.with(Sort.by(Sort.Direction.DESC,"created"));
        List<MovementTimeLine> movementTimeLineList = mongoTemplate.find(query, MovementTimeLine.class);
        log.debug("**********好友动态count{}*******movementTimeLineList{}***",count,movementTimeLineList.toString());
        //2.查询动态表
        List<Movement> movementList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(movementTimeLineList)) {
            //2.1 根据时间线表获取所有动态ids
            List<ObjectId> movementIds = movementTimeLineList.stream().map(MovementTimeLine::getMovementId).collect(Collectors.toList());
            //2.2根据所有动态ids查询动态表数据
            Query query2 = new Query();
            query2.addCriteria(Criteria.where("id").in(movementIds));
            query2.with(Sort.by(Sort.Direction.DESC,"created"));
            movementList = mongoTemplate.find(query2, Movement.class);
        }
        log.debug("**********movementList{}*******",movementList.toString());
        //3.构造PageResult对象返回
        return new PageResult<>(page,pageSize,count,movementList);
    }

    /**
     * 随机查询10个动态数据
     *
     * @return
     */
    @Override
    public PageResult<Movement> findPageMovementByRecommend() {
        //1.查询总记录数
        Query query = new Query();
        long count = mongoTemplate.count(query, Movement.class);
        //2.随机查询10个动态数据
        List<Movement> movementList = new ArrayList<>();
        if(count <10){
            movementList = mongoTemplate.findAll(Movement.class);
        }else{
            long start = RandomUtils.nextLong(0,count-9);
            query.skip(start).limit(10);
            movementList = mongoTemplate.findAll(Movement.class);
        }
        return new PageResult<>(1l,10l,count,movementList);
    }

    /**
     * 根据pids查询动态分页数据
     *
     * @param pidList
     * @return
     */
    @Override
    public PageResult<Movement> findPageMovementByPids(List<Long> pidList) {
        Query query = new Query();
        query.addCriteria(Criteria.where("pid").in(pidList));
        List<Movement> movementList = mongoTemplate.find(query, Movement.class);
        return new PageResult<>(1l,10l,10l,movementList);
    }

    /**
     * 单条动态
     * publishId:动态表主键id
     *
     * @param publishId
     */
    @Override
    public Movement findMovement(String publishId) {
        return mongoTemplate.findById(new ObjectId(publishId),Movement.class);
    }
}
